<template>
    <el-container style="height: 100vh;">
        <!-- 左侧菜单 -->
        <el-aside width="220px">
            <h3 style="padding: 20px; margin: 0;">管理中心</h3>
            <el-menu default-active="products" @select="switchTab">
                <el-menu-item index="products">商品管理</el-menu-item>
                <el-menu-item index="orders">订单管理</el-menu-item>
                <el-menu-item index="users">用户管理</el-menu-item>
                <el-menu-item index="statistics">数据统计</el-menu-item>
            </el-menu>
        </el-aside>

        <!-- 右侧主内容 -->
        <el-container>
            <el-header style="display: flex; justify-content: space-between; align-items: center;">
                <span>当前管理员：{{ adminName }}</span>
                <el-button @click="logout" type="danger" size="small">退出登录</el-button>
            </el-header>

            <!-- 商品管理 -->
            <el-main v-if="activeTab === 'products'">
                <h2>商品管理</h2>
                <el-select v-model="selectedCategory" placeholder="请选择分类" style="margin-bottom: 20px;">
                    <el-option v-for="cat in categories" :key="cat.value" :label="cat.label" :value="cat.value" />
                </el-select>
                <el-button type="success" @click="showAddProductModal = true">新增商品</el-button>

                <!-- 商品表格 -->
                <el-table :data="filteredProducts" border style="margin-top: 20px;">
                    <el-table-column prop="id" label="ID"></el-table-column>
                    <el-table-column prop="image_url" label="封面">
                        <template #default="{ row }">
                            <img :src="row.image_url" style="width: 100px; height: 100px;" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="名称"></el-table-column>
                    <el-table-column prop="price" label="价格"></el-table-column>
                    <el-table-column prop="stock_quantity" label="库存"></el-table-column>
                    <el-table-column prop="type" label="分类"></el-table-column>
                    <el-table-column label="状态">
                        <template #default="{ row }">
                            <el-tag :type="row.status ? 'success' : 'info'">{{ row.status ? '上架' : '下架' }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <el-button size="mini" @click="editProduct(row)">编辑</el-button>
                            <el-button size="mini" type="danger" @click="handledeleteProduct(row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 商品分类管理 -->
                <!-- <div style="margin-top: 40px;">
                    <h3>商品分类管理</h3>
                    <el-input v-model="newCategory" placeholder="输入新分类名" style="width: 200px;" />
                    <el-button @click="addCategory" type="primary" style="margin-left: 10px;">添加分类</el-button>
                    <el-button @click="removeCategory" type="danger" style="margin-left: 10px;">删除选中分类</el-button>
                    <el-select v-model="selectedCategoryId" multiple placeholder="选择分类">
                        <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
                    </el-select>
                </div> -->
            </el-main>

            <!-- 订单管理 -->
            <el-main v-else-if="activeTab === 'orders'">
                <h2>订单管理</h2>
                <el-table :data="orders" border>
                    <el-table-column prop="id" label="订单号"></el-table-column>
                    <el-table-column label="用户">
                        <template #default="{ row }">
                            {{ JSON.parse(row.userId).username }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="totalPrice" label="总金额"></el-table-column>
                    <el-table-column prop="status" label="状态"></el-table-column>
                    <el-table-column prop="createdAt" label="下单时间"></el-table-column>
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <el-button-group>
                                <el-button size="mini" @click="viewOrderDetails(row)">查看详情</el-button>
                                <el-button size="mini" type="primary"
                                    @click="showUpdateStatusModal(row)">更新状态</el-button>
                                <el-button size="mini" type="danger" @click="removeOrder(row.id)">删除</el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
                <el-dialog v-model="showOrderDetailModal" title="订单详情">
                    <div v-for="product in selectedOrder.products" :key="product.productId">
                        <p>商品名称：{{ product.name }}</p>
                        <p>单价：{{ product.price }}</p>
                        <p>数量：{{ product.quantity }}</p>
                        <p>小计：{{ product.price * product.quantity }}</p>
                    </div>
                    <p>订单总价：{{ selectedOrder.totalPrice }}</p>
                </el-dialog>
                <!-- 更新状态弹窗 -->
                <el-dialog v-model="showUpdateStatusModalVisible" title="更新订单状态">
                    <el-select v-model="newStatus" placeholder="请选择新状态">
                        <el-option label="待付款" value="待付款"></el-option>
                        <el-option label="待接单" value="待接单"></el-option>
                        <el-option label="已发货" value="已发货"></el-option>
                        <el-option label="已完成" value="已完成"></el-option>
                    </el-select>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="showUpdateStatusModalVisible = false">取消</el-button>
                            <el-button type="primary" @click="confirmUpdateStatus">确认</el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>


            <!-- 用户管理 -->
            <el-main v-else-if="activeTab === 'users'">
                <h2>用户管理</h2>
                <el-table :data="users" border style="margin-top: 20px;">
                    <el-table-column prop="id" label="ID"></el-table-column>
                    <el-table-column prop="username" label="用户名"></el-table-column>
                    <el-table-column prop="email" label="邮箱"></el-table-column>
                    <el-table-column prop="registeredAt" label="注册时间"></el-table-column>
                    <el-table-column label="角色">
                        <template #default="{ row }">
                            <el-tag :type="row.role === 'admin' ? 'success' : row.role === 'seller' ? 'warning' : ''">
                                {{ row.role === 'admin' ? '管理员' : row.role === 'seller' ? '卖家' : '买家' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态">
                        <template #default="{ row }">
                            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                                {{ row.status === 'active' ? '正常' : '已封禁' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <!-- 只有非自己账号才可操作 -->
                            <el-button v-if="row.username !== currentUser?.username" size="mini"
                                :type="row.status === 'active' ? 'danger' : 'primary'" @click="toggleBanUser(row)">
                                {{ row.status === 'active' ? '封禁' : '解封' }}
                            </el-button>
                            <el-button size="mini" type="danger" @click="deleteUser(row.userId)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-main>

            <!-- 数据统计 -->
            <el-main v-else-if="activeTab === 'statistics'">
                <h2>销售统计与分析</h2>
                <div style="display: flex; flex-direction: column;align-items: center; gap: 50px;">
                    <div ref="salesChart" style=" height: 400px; width: 800px;"></div>
                    <div ref="topProductsChart" style=" height: 400px; width: 800px;"></div>
                    <div ref="userGrowthChart" style=" height: 400px; width: 800px;"></div>
                </div>
            </el-main>
        </el-container>

        <!-- 新增/编辑商品模态框 -->
        <el-dialog v-model="showAddProductModal" title="新增商品">
            <el-form label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="currentProduct.name" />
                </el-form-item>
                <el-form-item label="图片">
                    <el-upload action="" :auto-upload="false" :show-file-list="false" :on-change="handleFileChange"
                        :before-upload="beforeUpload">
                        <img v-if="currentProduct.image_url" :src="currentProduct.image_url" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="价格">
                    <el-input-number v-model.number="currentProduct.price" :precision="2" />
                </el-form-item>
                <el-form-item label="库存">
                    <el-input-number v-model.number="currentProduct.stock_quantity" />
                </el-form-item>
                <el-form-item label="分类">
                    <el-select v-model="currentProduct.type" placeholder="请选择分类">
                        <el-option label="食品" value="食品"></el-option>
                        <el-option label="物品" value="物品"></el-option>
                        <el-option label="娱乐" value="娱乐"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="currentProduct.status" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveProduct">保存</el-button>
                    <el-button @click="closeModal">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </el-container>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import axios from 'axios'
import { watch } from 'vue';


const router = useRouter()

// 当前激活的标签页
const activeTab = ref('products')

// 管理员信息
const adminName = ref('超级管理员')

// 商品数据
// const products = ref([
//     { id: 1, name: '巧克力蛋糕', price: 168, stock: 235, category: '食品', status: true },
//     { id: 2, name: '手机', price: 2999, stock: 136, category: '数码', status: true },
//     { id: 3, name: '电脑', price: 5999, stock: 59, category: '数码', status: false },
// ])
import { fetchProducts, addProduct, updateProduct, deleteProduct } from '@/api/product';
const products = ref([]);

onMounted(async () => {
    const response = await fetchProducts();
    products.value = response.data;
});

// 分类选项
const categories = [
    { label: '全部', value: '' },
    { label: '食品', value: '食品' },
    { label: '物品', value: '物品' },
    { label: '娱乐', value: '娱乐' }
];

// 当前选中的分类
const selectedCategory = ref('');

// 过滤后的商品列表
const filteredProducts = computed(() => {
    if (!selectedCategory.value) return products.value;
    return products.value.filter(p => p.type === selectedCategory.value);
});
const file = ref(null);

const handleFileChange = (uploadFile) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        currentProduct.value.image_url = e.target.result;
    };
    reader.readAsDataURL(uploadFile.raw);
    file.value = uploadFile.raw;
};

const beforeUpload = (file) => {
    const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt20M = file.size / 1024 / 1024 < 20;

    if (!isJPGOrPNG) {
        ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
        return false;
    }
    if (!isLt20M) {
        ElMessage.error('上传图片大小不能超过 20MB!');
        return false;
    }
    return true;
};

// 添加商品
async function saveProduct() {
    if (isEditing.value) {
        // 更新商品
        await updateProduct(currentProduct.value.id, currentProduct.value);
        ElMessage.success('商品更新成功');
    } else {
        // 添加商品
        await addProduct(currentProduct.value);
        ElMessage.success('商品添加成功');
    }
    // 重新获取商品列表
    const response = await fetchProducts();
    products.value = response.data;
    closeModal();
}
//编辑商品
function editProduct(product) {
    currentProduct.value = { ...product };
    isEditing.value = true;
    showAddProductModal.value = true;
}
//删除商品
async function handledeleteProduct(productId) {
    try {
        await deleteProduct(productId);
        ElMessage.success('商品删除成功');
        // 从本地商品列表中移除
        products.value = products.value.filter(p => p.id !== productId);
    } catch (error) {
        ElMessage.error('删除商品失败');
    }
}


// 商品分类
const newCategory = ref('')
const selectedCategoryId = ref([])

function addCategory() {
    if (newCategory.value) {
        const newId = Math.max(...categories.value.map(c => c.id)) + 1
        categories.value.push({ id: newId, name: newCategory.value })
        newCategory.value = ''
    }
}


function removeCategory() {
    categories.value = categories.value.filter(cat => !selectedCategoryId.value.includes(cat.id))
}

// 订单数据
// const orders = ref([
//     { orderId: '20250401001', userName: '张三', totalPrice: 100, status: '已完成', createdAt: '2025-04-01' },
//     { orderId: '20250401002', userName: '李四', totalPrice: 200, status: '已发货', createdAt: '2025-04-01' }
// ])

import { fetchOrders, updateOrderStatus, deleteOrder } from '@/api/order';

const orders = ref([]);

onMounted(async () => {
    const response = await fetchOrders();
    orders.value = response.data;
});
const showOrderDetailModal = ref(false);
const selectedOrder = ref(null);

function viewOrderDetails(order) {
    selectedOrder.value = order;
    showOrderDetailModal.value = true;
}

//更新状态
const showUpdateStatusModalVisible = ref(false);
const newStatus = ref('');
const currentOrderId = ref(null);

function showUpdateStatusModal(order) {
    currentOrderId.value = order.id;
    newStatus.value = order.status;
    showUpdateStatusModalVisible.value = true;
}

async function confirmUpdateStatus() {
    if (currentOrderId.value && newStatus.value) {
        await updateOrderStatus(currentOrderId.value, newStatus.value);
        // 更新本地订单状态
        const index = orders.value.findIndex(o => o.id === currentOrderId.value);
        if (index !== -1) {
            orders.value[index].status = newStatus.value;
        }
        ElMessage.success('订单状态更新成功');
    }
    showUpdateStatusModalVisible.value = false;
}

//  删除订单
async function removeOrder(id) {
    try {
        await deleteOrder(id);
        // 从本地订单列表中移除
        orders.value = orders.value.filter(o => o.id !== id);
        ElMessage.success('订单删除成功');
    } catch (error) {
        ElMessage.error('删除订单失败');
    }
}

// 用户数据
const users = ref([])
// 获取用户数据
async function fetchUsers() {
    try {
        const response = await axios.get('http://localhost:3000/users')
        users.value = response.data.map(u => ({
            ...u,
            status: u.status || 'active' // 默认状态为 active
        }))
    } catch (error) {
        console.error('获取用户失败', error)
    }
}

onMounted(() => {
    fetchUsers()
})
//  封禁/解封用户
function toggleBanUser(user) {
    const newStatus = user.status === 'active' ? 'banned' : 'active'

    axios.patch(`http://localhost:3000/users/${user.id}`, {
        status: newStatus
    }).then(() => {
        ElMessage.success(`用户 ${user.username} 已${newStatus === 'active' ? '解封' : '封禁'}`)
        // 更新本地列表
        const index = users.value.findIndex(u => u.id === user.id)
        if (index !== -1) {
            users.value[index].status = newStatus
        }
    }).catch(err => {
        ElMessage.error('操作失败，请重试')
        console.error(err)
    })
}
// 删除用户
function deleteUser(userId) {
    const userToDelete = users.value.find(u => u.id === userId)

    if (!userToDelete) {
        ElMessage.error("找不到该用户")
        return
    }

    if (currentUser.value?.id === userToDelete.id) {
        ElMessage.warning("不能删除自己")
        return
    }

    axios.delete(`http://localhost:3000/users/${userId}`).then(() => {
        ElMessage.success("用户已删除")
        // 从本地列表中移除
        users.value = users.value.filter(u => u.id !== userId)
    }).catch(err => {
        ElMessage.error("删除失败")
        console.error(err)
    })
}

// 热门商品
const topProducts = ref([
    { name: '苹果', sales: 500 },
    { name: '可乐', sales: 400 },
    { name: '耳机', sales: 300 }
])

// 模态框控制
const showAddProductModal = ref(false)
const currentProduct = ref({
    name: '',
    price: 0,
    stock: 0,
    type: '', // 替换为分类字段
    image_url: 'https://via.placeholder.com/300x300', // 默认图片
    shopName: '校麦网官方旗舰店',
    status: true
});
const isEditing = ref(false)



function logout() {
    localStorage.removeItem("isLoggedIn");
    localStorage.removeItem("currentUser");
    router.push("/main/home");
}

function closeModal() {
    showAddProductModal.value = false
    isEditing.value = false
    currentProduct.value = {}
}



// 图表初始化
const salesChart = ref(null)
const topProductsChart = ref(null)
const userGrowthChart = ref(null)
//  数据获取
async function fetchData() {
    try {
        const [ordersRes, usersRes] = await Promise.all([
            axios.get('http://localhost:3000/orders'),
            axios.get('http://localhost:3000/users')
        ])
        orders.value = ordersRes.data
        users.value = usersRes.data
        initCharts()
    } catch (error) {
        console.error('获取数据失败', error)
    }
}
// 初始化图表
function initCharts() {
    nextTick(() => { // 确保 DOM 更新后执行
        if (salesChart.value) { // 检查 salesChart 是否存在
            renderSalesTrendChart();
        }
        if (topProductsChart.value) { // 检查 topProductsChart 是否存在
            renderTopProductsChart();
        }
        if (userGrowthChart.value) { // 检查 userGrowthChart 是否存在
            renderUserGrowthChart();
        }
    });
}

// 切换标签页
function switchTab(tab) {
    activeTab.value = tab
    if (tab === 'statistics') {
        // 使用 nextTick 确保 DOM 更新后再初始化图表
        nextTick(() => {
            initCharts()
        })
    }
}

// 渲染销售趋势图表
function renderSalesTrendChart() {
    if (!salesChart.value) return; // 防止 DOM 不存在时报错

    // 过滤最近7天的订单
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const dailySales = {};

    orders.value.forEach(order => {
        const date = new Date(order.createdAt);
        if (date >= sevenDaysAgo && order.status !== '待接单') {
            const day = date.toISOString().split('T')[0];
            dailySales[day] = (dailySales[day] || 0) + order.totalPrice;
        }
    });

    const sortedDates = Object.keys(dailySales).sort();
    const seriesData = sortedDates.map(date => dailySales[date]);
    const xAxisData = sortedDates.map(date => date.slice(5));

    const chart = echarts.init(salesChart.value);
    chart.setOption({
        title: {
            text: '最近一周销售额趋势',
            left: 'center'
        },//让title居中

        tooltip: {},
        xAxis: { data: xAxisData },
        yAxis: { type: 'value' },
        series: [{ data: seriesData, type: 'line' }]
    });
}

// 渲染热门商品图表
function renderTopProductsChart() {
    if (!topProductsChart.value) return; // 防止 DOM 不存在时报错

    const productSales = {};

    orders.value.forEach(order => {
        const date = new Date(order.createdAt);
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

        if (date >= sevenDaysAgo && order.status !== '待接单') {
            order.products.forEach(p => {
                const key = p.productId;
                productSales[key] = {
                    name: p.name,
                    quantity: (productSales[key]?.quantity || 0) + p.quantity
                };
            });
        }
    });

    const topProducts = Object.values(productSales)
        .sort((a, b) => b.quantity - a.quantity)
        .slice(0, 5);

    const chart = echarts.init(topProductsChart.value);
    chart.setOption({
        title: {
            text: '热门商品排行榜（近7天）',
            left: 'center'
        },
        tooltip: {},
        xAxis: { data: topProducts.map(p => p.name) },
        yAxis: { type: 'value' },
        series: [{ data: topProducts.map(p => p.quantity), type: 'bar' }]
    });
}

// 渲染用户增长图表
function renderUserGrowthChart() {
    if (!userGrowthChart.value) return; // 防止 DOM 不存在时报错

    const userGrowth = {};

    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    users.value.forEach(user => {
        const regDate = new Date(user.registeredAt);
        if (regDate >= sevenDaysAgo) {
            const day = regDate.toISOString().split('T')[0];
            userGrowth[day] = (userGrowth[day] || 0) + 1;
        }
    });

    const sortedDates = Object.keys(userGrowth).sort();
    const seriesData = sortedDates.map(date => userGrowth[date]);
    const xAxisData = sortedDates.map(date => date.slice(5));

    const chart = echarts.init(userGrowthChart.value);
    chart.setOption({
        title: {
            text: '用户增长趋势（近7天）',
            left: 'center'
        },
        tooltip: {},
        xAxis: { data: xAxisData },
        yAxis: { type: 'value' },
        series: [{ data: seriesData, type: 'line' }]
    });
}

//  页面加载时初始化图表
let refreshInterval;

onMounted(() => {
    fetchData();
    refreshInterval = setInterval(fetchData, 24 * 60 * 60 * 1000); // 每天刷新一次
});

onUnmounted(() => {
    clearInterval(refreshInterval); // 组件卸载时清除定时器
});



// 在 onMounted 后添加 watch 监听
watch(
    () => orders.value,
    () => {
        if (activeTab.value === 'statistics') {
            initCharts(); // 重新初始化所有图表
        }
    },
    { deep: true }
);

watch(
    () => users.value,
    () => {
        if (activeTab.value === 'statistics') {
            initCharts(); // 重新初始化用户增长图
        }
    },
    { deep: true }
);

</script>


<style scoped>
.el-aside {
    background-color: #f5f5f5;
    /* 浅白灰色 */
    border-right: 1px solid #eaeaea;
}

.el-aside h3 {
    color: #333;
    /* 深灰色文字，清晰易读 */
    margin: 0;
    padding: 20px;
    font-size: 18px;
}

.el-menu {
    border-right: none;
    background-color: transparent;
}

.el-menu-item,
.el-sub-menu {
    background-color: transparent;
}

.el-menu-item:hover,
.el-menu-item.is-active {
    background-color: #e0e0e0;
    /* 鼠标悬停或激活时稍微深一点的灰 */
    color: #000;
}

.el-header {
    background-color: #e76060;
    /* 稍深一点的浅红色 */
    color: #fff;
    font-size: 16px;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
